package br.com.intelsys.security.itoken;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.validator.GenericValidator;

public class TokenEncoder {

	private final String token;
	private final int codAux;
	private final String encodedToken;

	TokenEncoder(String token, int codAux) throws ITokenNotFoundException {
		this.token = token;
		this.codAux = codAux;
		if (GenericValidator.isBlankOrNull(token)) {
			throw new ITokenNotFoundException();
		}
		this.encodedToken = getMergedToken(token, codAux);
	}

	public TokenEncoder(String encodedToken) throws ITokenNotFoundException {
		this.encodedToken = encodedToken;
		String[] values = getUnmergedToken(encodedToken);
		if (values.length == 2) {
			this.token = values[0];
			int codAuxTmp;
			try {
				codAuxTmp = Integer.parseInt(values[1]);
			} catch (NumberFormatException e) {
				throw new ITokenNotFoundException();
			}
			this.codAux = codAuxTmp;
			if (GenericValidator.isBlankOrNull(this.token)) {
				throw new ITokenNotFoundException();
			}
		} else {
			throw new ITokenNotFoundException();
		}
	}

	private String getMergedToken(String token, int codAux) {
		StringBuilder sb = new StringBuilder();
		sb.append(token);
		sb.append(';');
		sb.append(codAux);
		StringBuilder sb64 = new StringBuilder();
		sb64.append((new String(Base64.encodeBase64(sb.toString().getBytes()))));
		sb64.reverse();
		return sb64.toString().replaceAll("=", "!");
	}

	private String[] getUnmergedToken(String mergedToken) {
		if (GenericValidator.isBlankOrNull(mergedToken)) {
			return new String[0];
		}
		StringBuilder sb64 = new StringBuilder(mergedToken.replaceAll("!", "="));
		sb64.reverse();
		try {
			return (new String(Base64.decodeBase64(sb64.toString().getBytes())))
					.split(";");
		} catch (ArrayIndexOutOfBoundsException e) {
			return new String[0];
		}
	}

	public String getToken() {
		return token;
	}

	public int getCodAux() {
		return codAux;
	}

	public String getEncodedToken() {
		return encodedToken;
	}

}
